package com.ledim.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.ledim.activity.base.LeDimBaseActivity;
import com.ledim.adapter.RoomPlayListAdapter;
import com.ledim.bean.ChatRoomBean;
import com.ledim.bean.RoomInfoResponse;
import com.ledim.bean.RoomPlayVideoBean;
import com.ledim.bean.RoomPlaylistResponse;
import com.ledim.bean.base.BaseResultDataInfo;
import com.ledim.ledimview.RoomPlayListAddView;
import com.ledim.ledimview.RoomTitleView;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimApiServiceUtils;
import com.ledim.service.LedimHttpObserver;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.LogUtil;
import com.ledim.utils.ToastUtil;
import com.ledim.widget.view.IXListViewListener;
import com.ledim.widget.view.XListView;
import com.letv.android.client.LetvSDK;
import com.letv.android.client.activity.ChooseRoomPicActivity;
import com.letv.android.young.client.R;
import com.letv.core.bean.IVideo;
import java.io.File;
import java.util.ArrayList;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 放映厅详情页
 */
public class RoomActivity extends LeDimBaseActivity implements IXListViewListener {

    public static final String ROOM_ID = "room_id";
    public static final String MY_ROOM_FLAG = "my_room_flag";
    public static final int REQUESTCODE_ROOM = 100;
    private RoomTitleView mRoomTitleView;
    private RoomPlayListAddView mRoomAddListView;
    private View mRoomCoverLayout;
    private View mRoomEmptyLayout;
    private XListView mListView;
    private View mStartPlay;
    private TextView mTitle;
    private TextView mStartBg;
    private TextView mEntryRoom;
    private ImageView mBack;
    private String mNameContent;
    private String mDescContent;
    private ChatRoomBean mRoom;
    private int mRoomStatus;
    private RoomPlayListAdapter mAdapter;
    private String mImagePath;
    private ArrayList<RoomPlayVideoBean> mWaitPlayLists = new ArrayList<RoomPlayVideoBean>();
    private boolean isMe;
    private ChatRoomBean mChatRoomBean;
    private boolean mFromPushMsg;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_room;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    private void initView() {
        mRoom = (ChatRoomBean) getIntent().getSerializableExtra(ROOM_ID);
        mFromPushMsg = getIntent().getBooleanExtra(ConstantUtil.FROM_PUSH_MSG, false);
        isMe = getIntent().getBooleanExtra(MY_ROOM_FLAG, false);
        mRoomTitleView = (RoomTitleView) View.inflate(this, R.layout.room_title_view, null);
        mRoomAddListView =
                (RoomPlayListAddView) View.inflate(this, R.layout.room_play_add_view, null);
        mListView = (XListView) findViewById(R.id.listview_room_playlist);
        mTitle = (TextView) findViewById(R.id.title);
        mEntryRoom = (TextView) findViewById(R.id.entry_room);
        mStartPlay = findViewById(R.id.start_end_play);
        mStartBg = (TextView) findViewById(R.id.start_end_play_bg);
        mBack = (ImageView) findViewById(R.id.back_image);
        mRoomCoverLayout = mRoomTitleView.findViewById(R.id.room_cover_layout);
        mRoomEmptyLayout = mRoomAddListView.findViewById(R.id.lists_emptyLayout);

        mRoomTitleView.setVisibility(View.GONE);
        mRoomEmptyLayout.setVisibility(View.GONE);
        mStartPlay.setVisibility(View.GONE);
        mEntryRoom.setVisibility(View.GONE);
        mRoomAddListView.setVisibility(View.GONE);
        mStartBg.setOnClickListener(this);
        mBack.setOnClickListener(this);
        mEntryRoom.setOnClickListener(this);

        mListView.setPullRefreshEnable(false);
        mListView.setXListViewListener(this, 0);
        mListView.addHeaderView(mRoomTitleView);
        mListView.addHeaderView(mRoomAddListView);
        mListView.setAdapter(null);
        if (!isMe) {//别人的放映厅
            mTitle.setText(mRoom.name);
            mStartPlay.setVisibility(View.GONE);
            mRoomAddListView.bindData(mRoom, false);
            mEntryRoom.setVisibility(View.GONE);
        } else {//自己的放映厅
            mTitle.setText("编辑放映厅");
            mRoomCoverLayout.setOnClickListener(this);
            mEntryRoom.setVisibility(View.GONE);
            mRoomAddListView.bindData(mRoom, true);
        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (mFromPushMsg && MainActivity.getInstance() == null) {
            upToHome(MainActivity.class);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isMe) {//别人的放映厅
            getUserRoomInfo();
        } else {//自己的放映厅
            getMyRoomInfo();
        }

    }

    /**
     * 获取Room信息
     */
    public void getMyRoomInfo() {
        LedimApiServiceUtils.getMyRoomInfo(new LedimHttpObserver<RoomInfoResponse>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }

            @Override
            public void onNext(RoomInfoResponse response) {
                super.onNext(response);
                if (response.success) {
                    mRoomStatus = response.data.status;
                    if (mRoom == null) {
                        mRoomAddListView.bindData(response.data, true);
                    }
                    mStartPlay.setVisibility(View.VISIBLE);
                    if (response.data.status == 1) {
                        mStartPlay.setVisibility(View.GONE);
                        mStartBg.setText("结束放映");
                    } else {
                        mStartBg.setText("开始放映");
                    }
                    mChatRoomBean = response.data;
                    mRoomTitleView.bindData(true, response.data);
                    mRoomTitleView.setVisibility(View.VISIBLE);
                    getRoomPlayList();
                }
            }
        });
    }

    private RoomPlaylistResponse mListResponse;

    /**
     * 获取播放列表
     */
    private void getRoomPlayList() {
        LedimApiServiceUtils.getRoomPlayList(mRoom.roomId, new LedimHttpObserver<RoomPlaylistResponse>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }

            @Override
            public void onNext(RoomPlaylistResponse roomPlaylistResponse) {
                super.onNext(roomPlaylistResponse);
                if (roomPlaylistResponse.success && roomPlaylistResponse.data != null) {
                    mListResponse = roomPlaylistResponse;
                    mRoomAddListView.setVisibility(View.VISIBLE);
                    showPlayLists(roomPlaylistResponse.data);
                }
            }
        });
    }

    public void getUserRoomInfo() {
        Subscription subscribe = LedimApiServiceFactory.createService(ApiService.class)
                                                       .getLedimRoomInfo(mRoom.roomId)
                                                       .observeOn(AndroidSchedulers.mainThread())
                                                       .subscribeOn(Schedulers.io())
                                                       .subscribe(new Observer<RoomInfoResponse>() {
                                                           @Override
                                                           public void onCompleted() {

                                                           }

                                                           @Override
                                                           public void onError(Throwable e) {
                                                               LogUtil.e("onError--" +
                                                                       e.getMessage());
                                                           }

                                                           @Override
                                                           public void onNext(
                                                                   RoomInfoResponse response) {
                                                               LogUtil.e("ccx -- " +
                                                                       response.toString());
                                                               if (response.success) {
                                                                   getRoomPlayList();
                                                                   mRoomTitleView.setVisibility(View.VISIBLE);
                                                                   mRoomTitleView.bindData(false, response.data);
                                                               }

                                                           }

                                                       });
    }

    @Override
    public void onRefresh(int id) {

    }

    @Override
    public void onLoadMore(int id) {

    }

    /**
     * @param cover
     *         修改Room封面
     */
    private void modifyRoomCover(File cover) {
        LedimApiServiceFactory.createService(ApiService.class)
                              .modifyRoomCover(mRoom.roomId, RequestBody.create(MediaType.parse("image/jpg"), cover))
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<BaseResultDataInfo<ChatRoomBean>>() {
                                  @Override
                                  public void onNext(
                                          BaseResultDataInfo<ChatRoomBean> chatRoomBeanBaseResultDataInfo) {
                                      super.onNext(chatRoomBeanBaseResultDataInfo);
                                      if (chatRoomBeanBaseResultDataInfo != null &&
                                              chatRoomBeanBaseResultDataInfo.success) {
                                          ToastUtil.toast("放映厅封面修改成功");
                                          Bitmap bm = BitmapFactory.decodeFile(mImagePath);
                                          mRoomTitleView.setRoomCover(bm);
                                      }
                                  }

                                  @Override
                                  public void onError(Throwable e) {
                                      super.onError(e);
                                  }
                              });
    }

    /**
     * 启动机器人
     */
    public void startRoomRobot() {
        LedimApiServiceFactory.createService(ApiService.class).startRoomRobot(mRoom.roomId)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver());
    }

    //播放列表展示
    private void showPlayLists(ArrayList<RoomPlayVideoBean> data) {
        if (data != null && data.size() != 0) {
            mStartBg.setClickable(true);
            mStartBg.setBackgroundResource(R.drawable.rect_round_can_start_play_bg);
            mRoomEmptyLayout.setVisibility(View.GONE);
            mWaitPlayLists.clear();
            mWaitPlayLists.addAll(data);
            if (mRoomStatus == 1) {//
                if (mRoom == null) {
                    mRoomAddListView.setEditButtonVisible();
                } else {
                    for (int i = 0; i < mWaitPlayLists.size(); i++) {
                        if (mWaitPlayLists.get(i).play_status == 0) {
                            mWaitPlayLists.get(i).play_status = -1;
                            break;
                        }
                    }
                }

            }

            if (mAdapter == null) {
                mAdapter = new RoomPlayListAdapter(this, mWaitPlayLists);
                mListView.setAdapter(mAdapter);
            } else {
                mAdapter.setDatas(mWaitPlayLists);
            }
        } else {
            mStartBg.setClickable(false);
            mStartBg.setBackgroundResource(R.drawable.rect_round_start_play_bg);
            mRoomEmptyLayout.setVisibility(View.VISIBLE);
            mWaitPlayLists.clear();
            mAdapter.setDatas(mWaitPlayLists);

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_image:
                if (mFromPushMsg && MainActivity.getInstance() == null) {
                    upToHome(MainActivity.class);
                }
                finish();
                break;
            case R.id.room_cover_layout:
                //choosePicture();
                Intent mIntent = new Intent(this, ChooseRoomPicActivity.class);
                mIntent.putExtra(ConstantUtil.MY_ROOM_ID, mRoom.roomId);
                mIntent.putExtra(ConstantUtil.MY_ROOM_URLS, getPlayListIds());
                startActivityForResult(mIntent, ConstantUtil.CHOOSE_FILE_PATHREQUEST);
                break;
            case R.id.start_end_play_bg:
                if (mRoomStatus == 0) {
                    if (mRoomTitleView.getRoomCover()) {
                        modifyRoomState("1");
                    } else {
                        ToastUtil.toast("请设置放映厅封面");
                    }
                }
                break;
            case R.id.entry_room:
                if (mRoomStatus == 1) {
                    IVideo video1 = new IVideo();
                    video1.setmVid(0);
                    LetvSDK.getInstance()
                           .playRoom(this, video1, mChatRoomBean, true, false, mFromPushMsg);
                    //是自己的
                }
                break;
        }
    }

    /**
     * @param status
     *         1 开启 0关闭
     *         开启或者关闭放映厅
     */
    private void modifyRoomState(String status) {
        LedimApiServiceUtils.modifyRoomStatus(mRoom.roomId, status, new LedimHttpObserver<BaseResultDataInfo<ChatRoomBean>>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }

            @Override
            public void onNext(BaseResultDataInfo<ChatRoomBean> chatRoomBeanBaseRequestData) {
                super.onNext(chatRoomBeanBaseRequestData);
                if (chatRoomBeanBaseRequestData.success) {
                    mRoomStatus = chatRoomBeanBaseRequestData.data.status;
                    if (mRoomStatus == 1) {
                        startRoomRobot();
                        finish();
                        IVideo roomVideo = new IVideo();
                        roomVideo.setmVid(0);
                        LetvSDK.getInstance()
                               .playRoom(RoomActivity.this, roomVideo, chatRoomBeanBaseRequestData.data, true, true, mFromPushMsg);

                    } else {
                        mStartBg.setText("开始放映");
                    }
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RoomActivity.REQUESTCODE_ROOM) {
            if (resultCode == RoomNameActivity.REQUESTCODE_ROOM_NAME) {
                mNameContent = data.getStringExtra("content");
                mRoomTitleView.setRoomTitle(mNameContent);
            } else if (resultCode == RoomDescActivity.REQUESTCODE_ROOM_DESC) {
                mDescContent = data.getStringExtra("content");
                mRoomTitleView.setRoomDesc(mDescContent);
            }
        }
        if (resultCode == ConstantUtil.CHOOSE_FILE_PATHRESPONSE) {
            //通过拍照或者选择图库上传文件
            mImagePath = data.getStringExtra(ConstantUtil.ZOOM_FILE_PATH);
            File cover = new File(mImagePath);
            if (mChatRoomBean.roomId != null) {
                modifyRoomCover(cover);
            }
        } else if (resultCode == ConstantUtil.CHOOSE_PICURL_RESPONSE) {
            // 通过获取网络图片--进行设置封面
            mRoomTitleView.setRoomCover(data.getStringExtra(ConstantUtil.CHOOSE_URL_PATH));
        }

    }

    private String getPlayListIds() {
        String urls = "";
        if (mListResponse != null && mListResponse.data != null) {
            for (RoomPlayVideoBean data : mListResponse.data) {
                urls = urls + data.submedia + ",";
            }
        }
        if (!TextUtils.isEmpty(urls)) {
            urls = urls.substring(0, urls.length() - 2);
        }
        return urls;
    }

}
